package org.lwj.logger.support;

import java.io.IOException;
import java.net.URI;

import org.lwj.logger.util.Constant;
import org.lwj.logger.util.Util;
import org.lwj.logger.mdc.LogMdc;
import org.lwj.logger.name.AppNameLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.web.client.RestTemplate;

public class LogRestTemplate extends RestTemplate {
	private static final Logger logger = LoggerFactory.getLogger(LogRestTemplate.class);
	private static String appName = AppNameLoader.appName();

	@Override
	protected ClientHttpRequest createRequest(URI uri, HttpMethod method) throws IOException {
		ClientHttpRequest request = super.createRequest(uri, method);
		try {
			String logid = LogMdc.get(Constant.LogId);
			if (Util.isEmpty(logid)) {
				logid = Util.logId();
			}
			logger.info("LogRestTemplate appName logid : " + appName + " " + logid);
			request.getHeaders().set(Constant.AppName, appName);
			request.getHeaders().set(Constant.LogId, logid);
		} catch (Exception e) {
			logger.error("LogRestTemplate createRequest error", e);
		}
		return request;
	}

}
